package com.xc.pay.weixin.v2;

import com.xc.pay.common.MessageTemplate;
import com.xc.pay.weixin.modal.v2.WxQueryModal;
import com.xc.pay.weixin.util.HttpUtils;
import com.xc.pay.weixin.util.XMLUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Filename: WxQueryOrder.java <br>
 *
 * <p>Description: 微信查询订单<br>
 *
 * @author: rongrong <br>
 * @version: 1.0 <br>
 */
@Slf4j
public class WxQueryOrder {

  public HashMap orderPayQuery(WxQueryModal modal) {
    HashMap<String, Object> map = new HashMap<>();
    log.info("[/order/pay/query]");
    //    if (StringUtils.isEmpty(modal.getTradeno())) {
    //      map.put("status", 500);
    //      map.put("msg", "订单号不能为空");
    //      return map;
    //    }
    Map<String, String> restmap = null;
    try {
      SortedMap<String, Object> parm = new TreeMap<String, Object>();
      //      parm.put("appid", modal.getAppid());
      //      parm.put("mch_id", modal.getMchId());
      //      parm.put("out_trade_no", modal.getTradeno());
      //      parm.put("nonce_str", WxToolUtil.getNonce_str());
      //      parm.put("sign", SignCreateUtil.getSign(parm, modal.getKey()));

      String restxml = HttpUtils.post(MessageTemplate.ORDER_PAY_QUERY, XMLUtil.parseXML(parm));
      restmap = XMLUtil.parseMap(restxml);
    } catch (Exception e) {
      log.error(e.getMessage(), e);
    }
    if (restmap != null
        && "SUCCESS".equals(restmap.get("return_code"))
        && "SUCCESS".equalsIgnoreCase(restmap.get("result_code").toString())) {
      String message = restmap.get("trade_state_desc").toString();
      // 订单查询成功 处理业务逻辑
      log.info("订单查询：订单" + restmap.get("out_trade_no") + "支付成功");
      String trade_state = restmap.get("trade_state").toString();
      Integer state = 0;
      if ("SUCCESS".equalsIgnoreCase(trade_state)) {
        trade_state = "支付成功";
        state = 200;
      } else if ("REFUND".equalsIgnoreCase(trade_state)) {
        trade_state = "转入退款";
        state = 250;
      } else if ("NOTPAY".equalsIgnoreCase(trade_state)) {
        trade_state = "订单未支付";
        state = 300;
      } else if ("CLOSED".equalsIgnoreCase(trade_state)) {
        trade_state = "订单已关闭";
        state = 350;
      } else if ("REVOKED".equalsIgnoreCase(trade_state)) {
        trade_state = "取消支付";
        state = 400;
      } else if ("USERPAYING".equalsIgnoreCase(trade_state)) {
        trade_state = "用户支付中";
        state = 450;
      } else if ("PAYERROR".equalsIgnoreCase(trade_state)) {
        trade_state = "支付失败";
        state = 500;
      }
      map.put("status", state);
      map.put("msg", trade_state);
    } else {
      map.put("status", 500);
      map.put("msg", "订单支付失败");
    }
    return map;
  }
}
